// pages/order/index.js
import { request } from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      { id: 0, value: "全部", isActive: true },
      { id: 1, value: "待付款", isActive: false },
      { id: 2, value: "待收货", isActive: false },
      { id: 2, value: "退款/退货", isActive: false }
    ],
    orders:[]
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const token = wx.getStorageSync("token")
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index',
      });
      return
    }
    //获取当前页面栈。数组中第一个元素为首页，最后一个元素为当前页面
    let pages = getCurrentPages();
    // console.log(pages)
    //当前页面
    let currentPage = pages[pages.length - 1];
    // console.log(currentPage.options);
    const { type } = currentPage.options;
    this.changeTitleByType(type-1)
    this.getOrders(type);
  },

  //获取订单列表
  async getOrders(type) {
    const res = await request({ url: "/my/orders/all", data: { type } });
    // console.log(res);
    this.setData({
      orders:res.orders.map(v=>({...v,create_time_cn:(new Date(v.create_time*1000).toLocaleString())}))
    })
  },

  changeTitleByType(index){
    let tabs = JSON.parse(JSON.stringify(this.data.tabs))
    tabs.forEach((item, i) => i === index ? item.isActive = true : item.isActive = false)
    this.setData({
      tabs
    })
  },

  //title点击切换
  itemTap(e) {
    // console.log(e);
    const index = e.detail.index;
    this.changeTitleByType(index)
    //重新发请求
    this.getOrders(index+1)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})